import { defineStore } from 'pinia'
import { ref } from 'vue'
import { doctorApi } from '@/api'

export const useDoctorStore = defineStore('doctor', () => {
  const options = ref<any[]>([])
  const curOptionsKeyword = ref('')
  const allPartnerOptions = ref<any[]>([]) //全部合作人医师
  const allStaffOptions = ref<any[]>([]) //全部员工医师

  const fetchOptions = async (keyword: string) => {
    if (keyword == curOptionsKeyword.value && options.value.length > 0) {
      return options.value
    } else {
      options.value = await getProcessedOptions({ keyword })
      curOptionsKeyword.value = keyword
      return options.value
    }
  }

  const fetchOptionsByStaffType = async (staffType: number) => {
    if (staffType == 1) {
      return await fetchAllPartnerOptions()
    } else {
      return await fetchAllStaffOptions()
    }
  }

  const fetchAllPartnerOptions = async () => {
    if (allPartnerOptions.value.length > 0) {
      return allPartnerOptions.value
    } else {
      allPartnerOptions.value = await getProcessedOptions({ staffType: 1, isAll: true })
      return allPartnerOptions.value
    }
  }

  const fetchAllStaffOptions = async () => {
    if (allStaffOptions.value.length > 0) {
      return allStaffOptions.value
    } else {
      allStaffOptions.value = await getProcessedOptions({ staffType: 2, isAll: true })
      return allStaffOptions.value
    }
  }

  const getProcessedOptions = async (params: { keyword?: string; staffType?: number; isAll?: boolean }) => {
    try {
      const { data } = await doctorApi.getDoctorOptions(params)
      const processedData = data.map((item: any) => ({
        label: item.name + '(' + item.staffCode + ')',
        key: item.staffCode,
        value: item.staffCode,
      }))
      return processedData
    } catch (error) {
      console.error('获取医师选项表失败:', error)
    }
  }

  return {
    options,
    fetchOptions,
    allPartnerOptions,
    fetchAllPartnerOptions,
    allStaffOptions,
    fetchAllStaffOptions,
    fetchOptionsByStaffType,
  }
})
